<?php
namespace app\common\model\account;

use think\Model;
use app\common\model\orderdata\Goods;
class AccountEntrustUse extends Model
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'account_entrust_use';
    protected $pk    = 'Id';

    /**
     * 关联 台账连接表
     * @return [type] [description]
     */
    public function link()
    {
        return $this->hasMany('AccountLink','AccountEntrustUseId','Id');
    }
    public function goodinfo()
    {
        return $this->hasone('app\common\model\orderdata\Goods','GoodId','GoodId');
    }
    
    // 创建产生台账
    public static function createAccount($params)
    {
        if (empty($params['CompanyId'])) {
            return moerr('缺少关联企业');
        }
        $entrustusefile = ['Type','OrderListId','UseType','AcceptingUnitType','AcceptingUnitName','AcceptingUnitCode','ExemptionUnitName','AbroadUnitName','AbroadUnitCode','SourceBatchCode'];
        $data                    = new AccountEntrustUse();
        $data->GoodId            = $params['GoodId'];
        $data->GoodName          = $params['GoodName'];
        $data->BatchCode         = $params['BatchCode'];
        $data->AccountTime       = $params['AccountTime'];
        $data->EndFlag           = isset($params['EndFlag']) ? $params['EndFlag'] : 0;
        $data->CreatUserId       = $params['CreatUserId'];
        $data->UpNote            = isset($params['UpNote']) ? $params['UpNote'] : '';
        $data->UpdateTime        = date('Y-m-d H:i:s', time());
        $data->Quantity          = $params['Quantity'];
        $data->Unit              = $params['Unit'];
        $data->BoxBatchCode      = $params['BoxBatchCode'];
        $data->BoxType           = $params['BoxType'];
        $data->BoxCount          = $params['BoxCount'];
        //委外利用
        foreach ($entrustusefile as $fk => $fv) {
            $data->$fv = empty($params[$fv])?'':trim($params[$fv]);
        }
        if(empty($params['Type'])){
            $data->Type = '处置';
        }
        $data->CompanyId = $params['CompanyId'];
        $data->save();
        return $data->Id;
    }

    /**
     * 获取批次编码
     * @return [type] [description]
     */
    public static function getBatchCode($company_id, $time = '',$type = '')
    {
        if (empty($time)) {
            $time = time();
        }
        $today = date('Y-m-d', $time);
        if($type!=='利用'){
            $type='处置';
        }
        $count = AccountEntrustUse::where('AccountTime', '>', $today)->where('CompanyId', $company_id)->where('Type',$type)->where('AccountTime', '<', $today . ' 24:00')->count();
        $str = $type=='利用'?'LY':'CZ';
        return 'HWWW'.$str . date('YmdHi', $time) . sprintf("%03d", $count + 1);
    }

    /**
     * 获取包装物的批次编码
     * @return [type] [description]
     */
    public static function getBoxBatchCode($company_id)
    {
        $count = AccountEntrustUse::where('CompanyId', $company_id)->count();
        return $count + 1;
    }

}
